package com.huan.sliding.runner;

import com.huan.sliding.windowservice.SlidingWindowService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 验证限流
 *
 * @author huan.fu
 * @date 2024/11/17 - 17:46
 */
@Component
public class TestApplicationRunner implements ApplicationRunner {

    @Resource
    private SlidingWindowService slidingWindowService;

    @Override
    public void run(ApplicationArguments args) {
        new Thread(()-> {
            for (int i = 0; i < 5; i++) {
                slidingWindowService.allowForLua("request:ip");
                if (i % 5 == 0) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(()-> {
            for (int i = 0; i < 5; i++) {
                slidingWindowService.allow("request:ip");
                if (i % 5 == 0) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("over");
    }
}
